package ks.server.controllers.commands.general;

import java.util.Collection;

import ks.framework.common.Message;
import ks.framework.communicator.Communicator;
import ks.framework.debug.Debug;
import ks.framework.interfaces.IProcessMessage;
import ks.managers.table.Table;
import ks.managers.table.TableManager;
import ks.server.ServerContext;

import org.w3c.dom.Document;

/** Controller to handle logouts. */
public class LogoutController implements IProcessMessage {

	/** Primary agent to whom we can communicate our messages. */
	Communicator com;
	
	public LogoutController (Communicator com) {
		this.com = com;
	}
	
	public boolean process(Message m) {
		Debug.println ("Observe logout by: " + m.getOriginator());
		
		TableManager tm = ServerContext.getTableManager();
		
		Collection<Table> tables = tm.getAllTables();
		Collection<String> players;
		
		for (Table table : tables) {
			players = table.getPlayers();
			
			for (String player : players) {
				if (player.equalsIgnoreCase(m.getOriginator())) {
					StringBuilder sb = new StringBuilder("<request version='1.0' id='1'>");
			        sb.append("<left table=\"" + table.getId() + "\" player=\""+ m.getOriginator() + "\"/>");
			        sb.append("</request>");
			        Document d = Message.construct (sb.toString());
			        
			        // send to all clients...
			        Message r = new Message (d);
			        r.setBroadcast();
			        
			        com.distribute(r);
				}
			}
		}
		
		 // produce request.
        StringBuilder sb = new StringBuilder("<request version='1.0' id='1'>");
        sb.append("<output>");
        sb.append("<text>");
        sb.append(m.getOriginator() + " logged out");
        sb.append("</text></output></request>");
        Document d = Message.construct (sb.toString());
        
        // send to all clients...
        Message r = new Message (d);
        r.setBroadcast();
        
        return com.distribute(r);
	}
}